//
//  LSRBaseViewController.m
//  BaiSiProject
//
//  Created by lshenrong on 16/7/21.
//  Copyright © 2016年 lshenrong. All rights reserved.
//

#import "LSRBaseViewController.h"
#import "LSRThemeCell.h"
#import <AFNetworking.h>
#import <MJExtension/MJExtension.h>
#import "LSRThemeItem.h"
#import "LSRThemeViewModel.h"
#import <MJRefresh/MJRefresh.h>
#import "LSREssenceViewController.h"

@interface LSRBaseViewController ()
@property(nonatomic,assign)NSInteger maxtime;
/**<#name#>*/
@property(strong,nonatomic  )MJRefreshNormalHeader  *header;

@property(strong,nonatomic  ) MJRefreshAutoNormalFooter *footer;

@property(nonatomic ,strong)NSMutableArray *themeViewModel;

/**<#name#>*/
@property(strong,nonatomic  )AFHTTPSessionManager  *manager ;




@end

@implementation LSRBaseViewController


-(NSMutableArray *)themeViewModel
{
    if (!_themeViewModel) {
        
        _themeViewModel=[NSMutableArray array];
    }
    
    return _themeViewModel;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //64是导航条（y=20,h=44）44是自定义的按钮条
    self.tableView.contentInset=UIEdgeInsetsMake(64+44, 0, 49, 0);
    //下载“全部”控制器的数据
    [self loadMoreData];
    self.tableView.rowHeight=100;
    
    self.tableView.backgroundColor=[UIColor grayColor];
    
    [self setRefreshView];
    
    
}
#pragma mark--loadData
-(void)setRefreshView
{
    //下拉刷新
    MJRefreshNormalHeader *header=[ MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.header=header;
    
    header.automaticallyChangeAlpha = YES;
    
    self.tableView.mj_header=header;
    //自动隐藏下拉控件
    
    //上拉加载更多数据
    MJRefreshAutoNormalFooter *footer= [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.footer=footer;
    footer.automaticallyChangeAlpha=YES;
    
    self.tableView.mj_footer=footer;
    
}


-(void)loadMoreData
{
    //为了避免冲突，取消下拉刷新
    [ self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    
    NSMutableDictionary *dict=[NSMutableDictionary dictionary];
    
    dict[@"a"]=@"newList";
    if ([self.parentViewController isKindOfClass:[LSREssenceViewController class]]) {
        dict[@"a"]=@"list";
    }
    dict[@"c"]=@"data";
    //1为全部，10为图片，29为段子，31为音频，41为视频，默认为1
    dict[@"type"]=@(self.type);
    dict[@"maxtime"]=@(self.maxtime);//字典数组之类的只存对象
    
    
    
    [manager  GET:LSRUrl parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //       [ self.footer  endRefreshing];
        
        [self.tableView.mj_footer endRefreshing];
        
        //取出上一页的最大maxtime作为参数传递
        self.maxtime=[responseObject[@"info"][@"maxtime"] integerValue];
        
        //字典数组转模型数组
        [responseObject writeToFile:@"/Users/lshenrong/Desktop/WWDC/voice.plist"atomically:YES];
        
        NSArray *themeList=[LSRThemeItem mj_objectArrayWithKeyValuesArray: responseObject[@"list"]];
        //模型数组转向模型视图数组
        for (LSRThemeItem *item in  themeList)
        {
            LSRThemeViewModel *VM=[[LSRThemeViewModel alloc] init];
            
            VM.themeItem=item;
            
            [self.themeViewModel addObject:VM];
            
        };
        
        //        NSLog(@"%@",self.themeViewModel);
        
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
        NSLog(@"%@",error);
        
        
        
        
    }];
    
    
    
    
    
    
    
    
}
#pragma mark----loadNewData
-(void)loadNewData
{
    [ self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    
    NSMutableDictionary *dict=[NSMutableDictionary dictionary];
    
    
    dict[@"a"]=@"newList";
    if ([self.parentViewController isKindOfClass:[LSREssenceViewController class]]) {
        dict[@"a"]=@"list";
    }

    dict[@"c"]=@"data";
    //1为全部，10为图片，29为段子，31为音频，41为视频，默认为1
    dict[@"type"]=@(self.type);
    dict[@"maxtime"]=@(self.maxtime);//字典数组之类的只存对象
    
    
    
    [manager  GET:LSRUrl parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        //结束刷新
        [self.tableView.mj_header endRefreshing];
        //取出上一页的最大maxtime作为参数传递
        self.maxtime=[responseObject[@"info"][@"maxtime"] integerValue];
        
        //字典数组转模型数组
        [responseObject writeToFile:@"/Users/lshenrong/Desktop/WWDC/voice.plist"atomically:YES];
        
        NSArray *themeList=[LSRThemeItem mj_objectArrayWithKeyValuesArray: responseObject[@"list"]];
        //模型数组转向模型视图数组
        for (LSRThemeItem *item in  themeList)
        {
            LSRThemeViewModel *VM=[[LSRThemeViewModel alloc] init];
            
            VM.themeItem=item;
            
            [self.themeViewModel addObject:VM];
            
        };
        
        //        NSLog(@"%@",self.themeViewModel);
        
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
        NSLog(@"%@",error);
        
        
        
        
    }];
    
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    NSLog(@"-----%@",NSStringFromUIEdgeInsets(self.tableView.contentInset));
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    
    //    NSLog(@"------%@",self.themeArray);
    
    return self.themeViewModel.count;
}


- (LSRThemeCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *ID=@"cell";
    
    
    LSRThemeCell *cell = [tableView dequeueReusableCellWithIdentifier:ID ];
    
    if (!cell) {
        cell=[[LSRThemeCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
        
    }
    
    cell.vm=self.themeViewModel[indexPath.row];
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self.themeViewModel[indexPath.row] cellH]+10;
    //    return 100;
    
}







@end
